package com.example.ivideo_2211a

import android.content.pm.ActivityInfo
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.SeekBar
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import com.example.common.mvi.BaseActivity
import com.example.common.mvi.SingleEvent
import com.example.ivideo_2211a.databinding.ActivityVideoDetailBinding
import com.example.ivideo_2211a.fabu.VideoFaEntityItem
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util

class VideoDetailActivity : BaseActivity<ActivityVideoDetailBinding, VideoDetailViewModel, VideoDetailIntent, VideoDetailViewState>() {
    override val viewModel: VideoDetailViewModel by lazy { ViewModelProvider(this)[VideoDetailViewModel::class.java] }

    private var exoPlayer: ExoPlayer? = null
    private var progressUpdateHandler: Handler? = null
    private var progressUpdateRunnable: Runnable? = null
    private var isFullscreen = false
    private var savedPlaybackPosition: Long = 0
    private var savedPlayWhenReady: Boolean = true
    private var currentVideoUrl: String? = null
    private var isPlay = false

    override fun onDestroy() {
        super.onDestroy()
        releasePlayer()
    }


    override fun getLayoutId(): Int = R.layout.activity_video_detail

    override fun setupViews() {
        setupButtonListeners()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        ViewCompat.setOnApplyWindowInsetsListener(binding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 获取视频ID
        val videoId = intent.getIntExtra("videoId", -1)
        if (videoId != -1) {
            // 发送加载视频详情的意图
            sendIntent(VideoDetailIntent.LoadVideoDetail(videoId))
        } else {
            Toast.makeText(this, "无效的视频ID", Toast.LENGTH_SHORT).show()
            finish()
        }
    }

    override fun renderViewState(state: VideoDetailViewState) {
        // 显示或隐藏加载指示器
        binding.loadingIndicator.visibility = if (state.isLoading) android.view.View.VISIBLE else android.view.View.GONE

        // 显示错误信息
        state.error?.let {
            Toast.makeText(this, it, Toast.LENGTH_SHORT).show()
        }

        // 显示视频详情
        state.videoDetail?.let {
            displayVideoDetail(it)
            // 播放视频
            it.videoUrl?.let { videoUrl ->
                if (currentVideoUrl != videoUrl) {
                    currentVideoUrl = videoUrl

                }
            }
        }
    }


    // 更新播放/暂停按钮状态
    private fun updatePlayPauseButton() {
        exoPlayer?.let {
            if (it.isPlaying) {
                binding.btnPlayPause.setImageResource(R.drawable.baseline_pause_circle_outline_24)
            } else {
                binding.btnPlayPause.setImageResource(R.drawable.baseline_play_circle_outline_24)
            }
        }
    }

    // 开始进度更新
    private fun startProgressUpdate() {
        if (progressUpdateHandler == null) {
            progressUpdateHandler = Handler(Looper.getMainLooper())
        }

        progressUpdateRunnable = object : Runnable {
            override fun run() {
                exoPlayer?.let { player ->
                    if (player.isPlaying) {
                        val currentPosition = player.currentPosition
                        binding.seekBar.progress = currentPosition.toInt()
                    }
                }
                progressUpdateHandler?.postDelayed(this, 500)
            }
        }

        progressUpdateRunnable?.let {
            progressUpdateHandler?.post(it)
        }
    }

    // 停止进度更新
    private fun stopProgressUpdate() {
        progressUpdateRunnable?.let {
            progressUpdateHandler?.removeCallbacks(it)
        }
    }

    // 暂停播放器
    private fun pausePlayer() {
        exoPlayer?.let {
            savedPlayWhenReady = it.playWhenReady
            it.pause()
            stopProgressUpdate()
        }
    }

    // 恢复播放器
    private fun resumePlayer() {
        exoPlayer?.let {
            it.playWhenReady = savedPlayWhenReady
            if (savedPlayWhenReady) {
                startProgressUpdate()
            }
            updatePlayPauseButton()
        }
    }

    // 初始化播放器
    private fun initializePlayer(videoUrl: String) {
        try {
            // 创建ExoPlayer实例
            exoPlayer = ExoPlayer.Builder(this).build()

            // 绑定到PlayerView
            binding.playerView.player = exoPlayer

            // 创建数据源工厂
            val dataSourceFactory = DefaultDataSourceFactory(this, Util.getUserAgent(this, "IVideo"))

            // 创建媒体资源
            val mediaSource = ProgressiveMediaSource.Factory(dataSourceFactory)
                .createMediaSource(MediaItem.fromUri(videoUrl))

            // 准备播放器
            exoPlayer?.setMediaSource(mediaSource)
            exoPlayer?.prepare()

            // 如果有保存的播放位置，则恢复播放
            if (savedPlaybackPosition > 0) {
                exoPlayer?.seekTo(savedPlaybackPosition)
            }

            // 设置播放状态
            exoPlayer?.playWhenReady = savedPlayWhenReady

            // 更新播放/暂停按钮状态
            updatePlayPauseButton()

            // 开始进度更新
            if (savedPlayWhenReady) {
                startProgressUpdate()
            }

            // 设置播放完成监听器
            exoPlayer?.addListener(object :  Player.Listener {
                override fun onPlaybackStateChanged(playbackState: Int) {
                    when (playbackState) {
                        Player.STATE_READY -> {
                            // 播放器准备就绪
                            binding.loadingIndicator.visibility = android.view.View.GONE
                        }
                        Player.STATE_BUFFERING -> {
                            // 正在缓冲
                            binding.loadingIndicator.visibility = android.view.View.VISIBLE
                        }
                       Player.STATE_ENDED -> {
                            // 播放完成
                            stopProgressUpdate()
                            binding.btnPlayPause.setImageResource(R.drawable.baseline_play_circle_outline_24)
                        }
                    }
                }
            })

            // 设置进度条拖动监听
            binding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
                override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                    if (fromUser) {
                        exoPlayer?.seekTo(progress.toLong())
                    }
                }

                override fun onStartTrackingTouch(seekBar: SeekBar?) {
                    stopProgressUpdate()
                }

                override fun onStopTrackingTouch(seekBar: SeekBar?) {
                    exoPlayer?.let {
                        if (it.isPlaying) {
                            startProgressUpdate()
                        }
                    }
                }
            })

            // 播放/暂停按钮点击事件
            binding.btnPlayPause.setOnClickListener {
                exoPlayer?.let {
                    if (it.isPlaying) {
                        pausePlayer()
                    } else {
                        resumePlayer()
                    }
                    updatePlayPauseButton()
                }
            }

            // 全屏按钮点击事件
            binding.btnFullscreen.setOnClickListener {
                toggleFullscreen()
            }

        } catch (e: Exception) {
            e.printStackTrace()
            Log.e("VideoDetailActivity", "设置ExoPlayer失败: ${e.message}")
        }
    }

    // 释放播放器
    private fun releasePlayer() {
        exoPlayer?.let {
            savedPlaybackPosition = it.currentPosition
            savedPlayWhenReady = it.playWhenReady
            it.release()
            exoPlayer = null
        }
        stopProgressUpdate()
        progressUpdateHandler = null
    }

    // 切换全屏
    private fun toggleFullscreen() {
        if (isFullscreen) {
            // 退出全屏
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
            isFullscreen = false
            binding.btnFullscreen.setImageResource(R.drawable.baseline_fullscreen_24)
        } else {
            // 进入全屏
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            isFullscreen = true
            binding.btnFullscreen.setImageResource(R.drawable.baseline_fullscreen_exit_24)
        }
    }

    override fun onPause() {
        super.onPause()
        if (Util.SDK_INT <= 23) {
            releasePlayer()
        }
        pausePlayer()
    }

    override fun onResume() {
        super.onResume()
        if ((Util.SDK_INT <= 23 || exoPlayer == null)) {
            currentVideoUrl?.let {
                initializePlayer(it)
            }
        } else {
            resumePlayer()
        }
    }

    private fun displayVideoDetail(video: VideoFaEntityItem) {
        video.viewCount+1
        // 显示视频标题
        binding.videoTitle.text = video.title
        // 显示视频描述
        binding.videoDescription.text = video.caption
        // 显示发布时间
        binding.publishTime.text = "发布时间: ${video.publishTime}"
        // 显示观看次数
        binding.viewCount.text = "观看次数: ${video.viewCount}"
        // 显示点赞数
        binding.likeCount.text = "点赞数: ${video.likeCount}"
        // 显示评论数
        binding.commentCount.text = "评论数: ${video.commentCount}"

        // 加载视频
        video.videoUrl?.let { videoUrl ->
            if (currentVideoUrl != videoUrl) {
                currentVideoUrl = videoUrl
                // 释放旧播放器
                releasePlayer()
                // 初始化新播放器
                initializePlayer(videoUrl)
            } else if (exoPlayer == null) {
                // 如果URL相同但播放器未初始化，则初始化
                initializePlayer(videoUrl)
            }
        }
    }

    private fun setupButtonListeners() {
        // 点赞按钮
        binding.btnLvjing.setOnClickListener {
            Toast.makeText(this, "滤镜功能开发中", Toast.LENGTH_SHORT).show()
        }

        // 评论按钮
        binding.btnFabu.setOnClickListener {
            Toast.makeText(this, "发布功能开发中", Toast.LENGTH_SHORT).show()
        }


    }
}